package com.heima.Servlet;

import com.heima.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 添加学生
 */
@WebServlet("/addStudentServlet")
public class addStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取注册页面的数据
        String username = req.getParameter("username");
        String age = req.getParameter("age");
        String score = req.getParameter("score");
        //创建学生对象并赋值
        Student student = new Student();
        student.setName(username);
        student.setAge(Integer.parseInt(age));
        student.setScore(Integer.parseInt(score));
        //使用io流把数据存储到本地文件
        BufferedWriter bw =new BufferedWriter(new FileWriter("d://student.txt",true));
        bw.write(student.getName()+","+student.getAge()+","+student.getScore());
        bw.newLine();
        bw.close();
        //通过定时刷新功能响应给浏览器
        resp.getWriter().write("添加成功。2秒后自动跳转到首页...");
        resp.setHeader("Refresh","2;URL="+req.getContextPath()+"/index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
